package com.jianye.recycdona;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.jianye.recycdona.control.bean.SMS;
import com.jianye.recycdona.control.http.CommentHttp;
import com.jianye.recycdona.control.http.UserOkHttp;
import com.jianye.recycdona.model.adapter.FragmentAdapter;
import com.jianye.recycdona.model.fragment.FindFragment;
import com.jianye.recycdona.model.fragment.HomeFragment;
import com.jianye.recycdona.model.fragment.MineFragment;
import com.jianye.recycdona.model.fragment.WelfareFragment;
import com.jianye.recycdona.model.utils.CheckNetWork;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;

import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 主类加载
     * */
    public static BottomNavigationView navigationView;
    private MenuItem menuItem;
    public static   ViewPager viewparge;
    private FragmentAdapter mFragmentAdapter;
    public static LinearLayout linearLayout_home;

    /**
     * 引导界面
     * */
    TextView ad_btn;
    LinearLayout linearLayout_yindao;
    /**
     * 登录界面
     */


    private EditText phone_ev;//手机号码
    private EditText code_et;//验证码
    private Button code_bt;
    private Button login_bt;//确定按钮

    public SharedPreferences sp;//自动登录
    private UserOkHttp myOkHttp;  //请求
    public static LinearLayout linearLayout_login;  //登录布局  gone visiblity
    //手机号**验证码
    private String phone;
    int Randomcode;  //随机码验证码
    private String codeinfo; //登录信息
    private int i;
    private List<SMS.ContentBean> listsms;
    private String acoun,url,secretkey,template;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        @SuppressLint("CommitPrefEdits")
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("initdata", false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        ActionBar actionBar=getSupportActionBar();

        if (actionBar!=null){
            actionBar.hide();
        }




        initFragment();//先初始化主页面

        /**
         * 加载登录界面
         */
        initView();


        /**
         * 引导界面
         */
        init();
        //注意sdk28会出错
        time_ad();//定时3m
    }

    /**
     * 登录初始化
     */
    private void initView() {

        //获取id
        phone_ev = (EditText) findViewById(R.id.phone_et);
        code_et = (EditText) findViewById(R.id.code_et);

        code_bt=findViewById(R.id.code_bt);
        login_bt=findViewById(R.id.login_btn);

        code_bt.setOnClickListener(this);
        login_bt.setOnClickListener(this);

        linearLayout_login=findViewById(R.id.linearlayout_login_container);//布局id

        myOkHttp = UserOkHttp.getMyOkHttp();//请求初始化


        //自动登录，密码进行存储
        sp = getSharedPreferences("config", MODE_PRIVATE);//confi 文件名

        boolean autocode = sp.getBoolean("logincode", false);//判断是否已经登录过


        //自动登录实现
        if (autocode){

            linearLayout_login.setVisibility(View.GONE);//隐藏登录界面
            linearLayout_home.setVisibility(View.VISIBLE);//显示home
        }


    }


    //登录操作
    private void login() {

        viewparge.setCurrentItem(0);
        navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye2);
        navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
        navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);
        navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);

        final String phone = phone_ev.getText().toString().trim();
        final String code = code_et.getText().toString().trim();

        if (!CheckNetWork.checkConnectNetwork(MainActivity.this)){
            Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
        }else if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
        }else if (!CheckNetWork.isValidPhoneNumber(phone)){
            Toast.makeText(this, "手机格式不正确", Toast.LENGTH_SHORT).show();
        }else if (TextUtils.isEmpty(code)){
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
        }else if (!code.equals(Randomcode+"")){
            MainActivity.show(MainActivity.this,"验证码出错了吧!");
        } else {

                    try {
                            //检查手机号是否注册
                            UserOkHttp.getMyOkHttp().chekPhone(phone);
                            //登录并注册
                            codeinfo= UserOkHttp.getMyOkHttp().Login(phone);
                    } catch (ExecutionException | InterruptedException e) {
                        e.printStackTrace();
                    }
                    //请求成功，存入
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("phone", phone);
                        editor.putString("username","环保新手");
                        editor.putInt("point",5);
                        editor.putBoolean("logincode", true);
                        editor.apply();

                        Log.e("登录信息","----------------------->"+phone+codeinfo);

                        //存储用户信息
                        try {
                            UserOkHttp.getMyOkHttp().getUserinfo(phone,sp);
                        } catch (ExecutionException | InterruptedException e) {
                            e.printStackTrace();
                        }



            // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(
                    MainActivity.this.getWindow().getDecorView().getWindowToken(), 0);
        }


        phone_ev.setText("");
        code_et.setText("");
        i=0;//结束60秒

        System.out.println("RecyclerUser-------------------------------"+codeinfo);
            linearLayout_login.setVisibility(View.GONE);//登录隐藏
            linearLayout_home.setVisibility(View.VISIBLE);//HOME显示




        }


    }

    //hander 定时操作
    @SuppressLint("HandlerLeak")
    private final Handler handler=new Handler(){
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    code_bt.setEnabled(false);//在60秒发送过程中button设置为不可点击
                    code_bt.setText(msg.obj+"秒");
                    break;
                case 1:
                    code_bt.setEnabled(true);//设置为可点击
                    code_bt.setText("发送验证码");
                    break;
                case 2:
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    //发送验证码，默认一个小时发送6次，超过发送失败
    private void sendCode() {

        try {
            listsms= CommentHttp.getMyOkHttp().getsmsapi();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }

        Log.e("getUrlsezi","-------------------------->"+listsms.size());
        if (listsms.get(0).getUrl()!=null){
             acoun= listsms.get(0).getAcount();
             url=listsms.get(0).getUrl();
             secretkey=listsms.get(0).getSecretkey();
             template=listsms.get(0).getTemplate();

        }
        // https://yiketianqi.com/api/sms?appid=45121489&appsecret=96nzoUY



        //获取手机号
         phone = phone_ev.getText().toString().trim();
        if (!CheckNetWork.checkConnectNetwork(MainActivity.this)) {
            Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
        } else if (!CheckNetWork.isValidPhoneNumber(phone)) {
            Toast.makeText(this, "手机格式不正确", Toast.LENGTH_SHORT).show();
        }else
            {

                    //开始发送
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Randomcode = CheckNetWork.random();
                            String smsUrl =url+"?"+"appid="+acoun+"&appsecret="+secretkey+"&code="+Randomcode+"&mobile="+phone+"&template_id="+template;
                            Log.d(TAG, "------------------------------------->smsUrl: "+smsUrl);
                            //接收返回信息
                            final int s=myOkHttp.sendcode(smsUrl);


                            //发送成功=0
                            if (s==0){
                                for ( i=60;i>0;i--){
                                    try {
                                        handler.obtainMessage(0,i).sendToTarget();
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                                handler.obtainMessage(1).sendToTarget();//60秒结束，handen传递1将text设置为true 可点击

                            }else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //显示
                                        Toast.makeText(MainActivity.this, "发送次数过多，请稍后再试", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                        }
                    }).start();

        }
    }


    //解决在子线程中调用Toast的异常情况处理
    public static void show(Context context, String text) {
        Toast toast = null;
        try {
            toast= Toast.makeText(context, text, Toast.LENGTH_LONG);
            toast.show();
        } catch (Exception e) {

            Looper.prepare();
            Toast.makeText(context, text, Toast.LENGTH_LONG).show();
            Looper.loop();
        }
    }

    /**
     * 引导界面定时操作
     */
    private void time_ad() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        linearLayout_yindao.setVisibility(View.GONE);
                    }
                });
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 3000);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("initdata", true);
    }


    //引导界面初始化
    private void init() {
        linearLayout_yindao =findViewById(R.id.liner_yindao_contatner);
        ad_btn = findViewById(R.id.ad_btn);
        linearLayout_yindao.setOnClickListener(this);
        ad_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //引导事件监听
        if (v.getId() == R.id.ad_btn) {
            linearLayout_yindao.setVisibility(View.GONE);
        }

        /**
         * 登录事件监听
         */
        loginListener(v);


    }

    /**
     * 登录监听
     */
    @SuppressLint("NonConstantResourceId")
    private void loginListener(View v) {

        switch (v.getId()) {
            case R.id.login_btn:
                login();//登录按钮
                break;
            case R.id.code_bt:
                sendCode();//发送验证码
                break;
        }
    }


    /**
     * 再按一次退出程序
     */
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)//event.getActivity()==KeyEvent.ACTION_DOWN
        {
            if((System.currentTimeMillis()-exitTime) > 2000)
            {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();

                exitTime = System.currentTimeMillis();

            } else
            {
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addCategory(Intent.CATEGORY_HOME);

                startActivity(home);

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    /**
     * 底部导航初始化
     */
    private void initFragment()
    {
        linearLayout_home=findViewById(R.id.home_container);//container
        navigationView =  findViewById(R.id.bnv_main);
        viewparge=findViewById(R.id.fl_main);
        navigationView.setItemIconTintList(null);

//        viewparge.setAdapter(mFragmentAdapter);
        viewparge.setOffscreenPageLimit(1);//预加载页数
//        navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
//        navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);
//        navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);

//        BottomNavigationViewHelper.disableShiftMode(navigationView);

        navigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @SuppressLint("NonConstantResourceId")
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {

                            case R.id.navigation_home:
                                viewparge.setCurrentItem(0);
                                navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye2);
                                navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
                                navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);
                                navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);
                                break;

                            case R.id.navigation_exchange:
                                viewparge.setCurrentItem(1);
                                navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye);
                                navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare2);
                                navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);
                                navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);
                                break;
                            case R.id.navigation_find:
                                viewparge.setCurrentItem(2);
                                navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye);
                                navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
                                navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai2);
                                navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);
                                break;

                            case R.id.navigation_personal:
                                viewparge.setCurrentItem(3);
                                navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye);
                                navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
                                navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);
                                navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren2);
                                break;

                        }
                        return false;
                    }
                });

        viewparge.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    navigationView.getMenu().getItem(0).setChecked(false);
                }

                menuItem = navigationView.getMenu().getItem(position);
                menuItem.setChecked(true);
                switch (position){
                    case 0:
                        menuItem.setIcon(R.drawable.img_zhuye2);
                        navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
                        navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_dongtai);
                        navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_geren);break;
                    case 1:
                        navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye);
                        navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare2);
                        navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);
                        navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);
                        break;
                    case 2:
                        navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye);
                        navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
                        navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai2);
                        navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);
                        break;
                    case 3:
                        navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye);
                        navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
                        navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);
                        navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren2);
                        break;
                }


            }



            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //禁止ViewPager滑动
//        viewPager.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });

        setupViewPager(viewparge);

    }

    //设置每个图标
    private void setupViewPager(ViewPager viewPager) {
        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());

        adapter.addFragment(HomeFragment.newInstance("首页"));
        adapter.addFragment(WelfareFragment.newInstance("福利"));
        adapter.addFragment(FindFragment.newInstance("动态"));
        adapter.addFragment(MineFragment.newInstance("我的"));
        viewPager.setAdapter(adapter);
    }


    /**
     * 重新配置每个按钮的图标
     */
    private void resetToDefaultIcon() {
        navigationView.getMenu().findItem(R.id.navigation_home).setIcon(R.drawable.img_zhuye);
        navigationView.getMenu().findItem(R.id.navigation_exchange).setIcon(R.drawable.walfare);
        navigationView.getMenu().findItem(R.id.navigation_find).setIcon(R.drawable.img_dongtai);
        navigationView.getMenu().findItem(R.id.navigation_personal).setIcon(R.drawable.img_geren);
    }


}
